<?php
class ListingsController extends AppController
{
	var $name = 'Listings';
	var $helpers = array('Form','Html','Cms.Index','Users.UserContent','Modules.Section','Rating.rating', 'Time', 'Votes.Vote','CustomFieldDisplay','ListingInformation');
	var $components = array('Auth','Session','RequestHandler','Email');
	var $indexMethods = array();
	protected $autoAdminActions = array('admin_bulkDelete','admin_bulkPublish','admin_bulkUnpublish');
	
	function beforeFilter()
	{
		$this->Auth->allow('tags','categoryListing','index','view','home','userFavorite','userListing','advancedSearch','compare','loadListing','suggest', 'getDirections');
		parent::beforeFilter();
		$this->indexMethods = cr('indexMethods.Listings');
		//@GEOMAP INTERSECTION.
		$this->helpers[] = "GeoMap";
	}
	
	function _appyHtmlEditorConfig()
	{
		if(cr('GeneralConfig.disable_html_editor'))
		{
			$this->Listing->setFieldProperties('description',array('type'=>'textarea'));
		}
	}
	
	function index($type = false)
	{
    	if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'listingIndex';
		}
		$this->viewFile = null;
		$listingConfig = cr('ListingConfig');
		$paginateLimit = $listingConfig['paginate_limit'];
		
		$this->Listing->setScope('published');
		$this->pageTitle = __('Listings');
		if(isset($this->params['named']['sort']) && $this->params['named']['sort'] == "Listing.is_featured")
		{
			unset($this->passedArgs['sort']);
			unset($this->passedArgs['direction']);
			unset($this->params['named']['sort']);
			unset($this->params['named']['direction']);
		}
		$this->paginate['order'] = array('Listing.is_featured DESC');
		$this->paginate['recursive'] = 0;
		$this->paginate['contain'] = array('ListCategory');
		$this->paginate['limit'] = $paginateLimit;
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$limit = null;
				if(isset($this->params['named']['limit']))
				{
					$limit = $this->params['named']['limit'];
				}
				$this->{$subMethodName}($limit);
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}		
		$listingData = $this->paginate();
		if($this->_isVarRequest())
		{
			return $listingData;
		}
		$hideRssFeed = $listingConfig['disable_listing_rss'];
		if($this->params['isAjax'])
		{
			$hideRssFeed = true;
		}
		$this->set('hideRssFeed',$hideRssFeed);	
		$this->_setViewType($listingConfig);
		$this->set(compact('listingData'));
		if(cr("DealConfig.enable_deals"))
		{
			$showDeals = false;
			$deals = array();
			if(!isset($this->params['requested']) || $this->params['requested'] != true)
			{
				$listingIdsForDeals = Set::extract($listingData,'{n}.Listing.id');
				
				$deals = cri("Deals.Deal")->getListingDeals($listingIdsForDeals);
				if(!empty($deals))
				{
					$showDeals = true;
					$deals = Set::combine($deals,'{n}.Deal.id','{n}');
				}
			}
			$this->set('deals',$deals);
			$this->set('showDeals',$showDeals);
		}

		//added for showing/change url of breadcrumbs on basis of category from where it was redirected
		if(cr("ListingConfig.allow_multiple_categories"))
		{ 
			$showAsListingCategory = false;
			if(isset($this->actionId) && $this->actionId == 'categorypages')
			{
				$showAsListingCategory = $this->actionParams['categorySlug'];
			}
			$this->set('showAsListingCategory',$showAsListingCategory);
		}
		//added for showing/change url of breadcrumbs on basis of category from where it was redirected
		
		$categoryIds = array();
		foreach ($listingData as $listing)
		{
			if(isset($listing["Listing"]["category_list"]) && $listing["Listing"]["category_list"])
			{
				$categoryIds = am($categoryIds, $listing["Listing"]["category_list"]);
			} else {
				$categoryIds = am($categoryIds, array($listing["Listing"]["list_category_id"]));
			}
		}
		$categoryIds = array_unique($categoryIds);
		$listingCategoriesData = $this->Listing->ListCategory->find("all",array("conditions"=>array("ListCategory.id"=>$categoryIds),"recursive"=>-1));
		if(!empty($listingCategoriesData))
		{
			$listingCategoriesData = Set::combine($listingCategoriesData,"{n}.ListCategory.id","{n}");
		}
		$this->set("listingCategoriesData",$listingCategoriesData);
		if($this->viewFile)
		{
			$this->render($this->viewFile);
		}
	}	
	
	function _setViewType($listingConfig)
	{
		$view_type = $listingConfig['view_type'];
		if(((isset($this->params['pass']['0']) && $this->params['pass']['0'] == 'search')))
		{
			$view_type = 'table_view';
		}
		$this->set("view_type",$view_type);
	}
	
	function add()
	{
		$this->pageTitle = __("Add Listing");
		if(cr('ListingConfig.listing_add_only_by_editor') == 1 && $this->Listing->User->isEditor($this->Session->read('Auth.User.id')) == false)
		{
			$this->__invalidUrl(__('Sorry, only editor can add listings.'),'/');
		}
		if(isset($this->params['isAjax']) && $this->params['isAjax'] == 1)
		{
			Configure::write('debug',0);
		}
		$step = 1;
		if(isset($this->data['Listing']['step']))
		{
			$step = $this->data['Listing']['step'];
			$goToNextStep = true;
			if($step == 1)
			{
				if(!isset($this->data['Listing']['categories']) || empty($this->data['Listing']['categories']))
				{
					$goToNextStep = false;
					$this->errorMsg(__("Category not selected", true));
				}
			}
			if($goToNextStep == true)
			{
				$step++;
			}
		}
		if($this->data)
		{
			if($step >= 3)
			{
				$this->listingAddSave();
			}
		}else
		{
			
		}
		if($step == 2 && !AppUtility::allowPaidListing())
		{
			$step++;
		}
		if($step > 1)
		{
			$this->prepareListingForm($this->data['Listing']['categories'],false,@$this->data['Listing']['plan_id']);
		}
		$this->set("step",$step);
		$categories = cri('ListCategory')->getOptions();
		$this->set('categories',$categories);
		$this->helpers[] = "PaidListings.PaidListing";
		
	}
	
	private function listingAddSave()
	{
		$categories = $this->data['Listing']['categories'];
		if(!is_array($categories))
		{
			$categories = array($categories);
		}
		$categories = array_values($categories);
		if(!$categories)
		{
			$this->Listing->invalidate("categories",__("Please select categories"));
			return false;
		}
		$plan = null;
		if(AppUtility::allowPaidListing() && $this->data && isset($this->data["ListingPlan"]['plan_id']))
		{
			$PlanModel = cri("PaidListings.Plan");
			$plan = $PlanModel->getNewTypePlanForListing($this->data["ListingPlan"]['plan_id'],$categories);
			$this->data['ListingPlan']['plan_id'] = $plan['Plan']['id'];
		}
		$this->prepareListingForm($this->data['Listing']['categories'],false,$plan);
		foreach((array)$this->data['Listing']['categories'] as $categoryId)
		{
			$this->data['Listing']['additional_categories'][] = array('list_category_id'=>$categoryId);
		}
		$categoryId = $categories[0];
		$this->data['Listing']['ip'] = Utility::getClientIP();
		$this->data['Listing']['list_category_id'] = $categoryId;
      	$this->data['Listing']['user_id'] = $this->Session->read("Auth.User.id");
		$reviewData = null;
		$proceedToSave = true;
		if(@$this->data['Review'])
		{
			$reviewData['Review'] = @$this->data['Review'];
			unset($this->data['Review']);
			if(cr("ListingConfig.add_review_with_listing") && isset($this->data['Listing']['add_review']) && $this->data['Listing']['add_review'])
			{
				$reviewData['Review']['user_id'] = $this->Session->read('Auth.User.id');
				$proceedToSave = $this->Listing->saveAll($this->data,array("validate"=>"only"));
				$proceedToSave = $proceedToSave && $this->Listing->Review->saveAll($reviewData,array("validate"=>"only"));
			}
		}
		$result = false;
		if($proceedToSave)
		{
			$result = $this->save($this->data,false,false);
		}
		$this->data = am($this->data,$reviewData);
		if($result)
		{
			$moderation = cr('ListingConfig.enable_moderation');
			if($moderation == false)
			{	
				$this->successMsg(__('Listing has been saved.'));	
			}else
			{			
				$this->successMsg(__('Your listing has been saved and will be published after moderation.'));
			}
			if(cr("ListingConfig.add_review_with_listing") && isset($this->data['Listing']['add_review']) && $this->data['Listing']['add_review'] && !empty($reviewData) && $this->Listing->id)
			{
				$isEditor = $this->Listing->User->isEditor($this->Session->read('Auth.User.id'));
				
				$reviewData['Review']['user_id'] = $this->Session->read('Auth.User.id');
				$reviewData['Review']['listing_id'] = $this->Listing->getLastInsertId();
				$reviewData['Review']['ip'] = Utility::getClientIP();
				$reviewData['Review']['status'] = Review::PUBLISHED;
				$reviewData['Review']['added_with_listing'] = true;
				if($moderation || (!$isEditor && cr("ReviewConfig.moderate_new_user_reviews")) || ($isEditor && cr("ReviewConfig.moderate_new_editor_reviews")))
				{
					$reviewData['Review']['status'] = Review::UNPUBLISHED;
				}
				$this->Listing->Review->create();
				$this->Listing->Review->saveAll($reviewData);
			}
			$this->__afterAdd();
			$this->redirect(array('controller'=>'listings','action'=>'index'));
		}
		return false;
	}
	
	protected function __afterAdd()
	{
		$this->__sendApprovalEmail($this->data);
		//Configure::write('debug',2);
		if(AppUtility::allowPaidListing())
		{
			$planId = null;
			if(isset($this->data["ListingPlan"]['plan_id']))
			{
				$planId = $this->data["ListingPlan"]['plan_id'];
			}
			$PlanModel = cri("PaidListings.Plan");
			$plan = $PlanModel->getNewTypePlanForListing($planId,$this->data['Listing']['list_category_id']);	
			if($plan)
			{
				$ListingPlanModel = cri("PaidListings.ListingPlan");
				$listingPlanId = $ListingPlanModel->initPlanForListing($plan['Plan']['id'],$this->Listing->id,$this->Session->read("Auth.User.id"));
				//if free plan, implement plan right away and don't make user as owner.
				//Create A Claim also.
				$ClaimModel = cri("ListingClaim");
				$ClaimModel->create();
				$claimInfo = array("name"=>$this->Session->read("Auth.User.username"),
						'explanation' => sprintf(__("Ordered plan : %s while adding listing"),$plan['Plan']['title']),
						'email' => $this->Session->read("Auth.User.email"),
						'user_id'=>$this->Session->read("Auth.User.id"),
						'status'=>ListingClaim::STATUS_PENDING,
						'listing_id' => $this->Listing->id,
						
				);
				//Disabled as decided.
				//$ClaimModel->create();
				//$ClaimModel->save(array($ClaimModel->alias => $claimInfo),array("validate"=>false));
				if($plan['Plan']['payment_type'] == Plan::PAYMENT_TRIAL)
				{
					$ListingPlanModel->orderFreePlan($listingPlanId);
					$ListingPlanModel->activatePlan($listingPlanId);
                    if(cr('ListingConfig.enable_moderation') && $plan['Plan']['disable_moderation'])
					{
						$this->successMsg(__('Listing has been saved.'));
                        $this->redirect(array('controller'=>'listings','action'=>'index'));
					}
				}else
				{
					$ownerId = $this->Session->read("Auth.User.id");
					$this->Listing->saveField("owner_candidate_id",$ownerId);
					$Order = cri("PaidListings.Order");
					$orderId = $Order->initOrder($listingPlanId);
					$msg = __("Listing has been added. Please continue with payment process.");
					if(cr('ListingConfig.enable_moderation') && !$plan['Plan']['disable_moderation'])
					{
						$msg = __("Listing has been sent to admin for moderation. Please continue with payment process");
					}
					$this->successMsg($msg);
					$this->redirect(array("action"=>"invoice",'controller'=>"orders",'plugin'=>"paid_listings",$orderId));
				}
			}
		}
	}
	function __sendApprovalEmail($params)
	{
		if(is_numeric($params))
		{
			$this->Listing->recursive = -1;
			$listingData = $this->Listing->findById($params);
			$userData = $listingData['Listing']['poster'];			
		}else
		{
			$listingData = $params;
			$userData = $this->Session->read('Auth.User');
		} 	
		$emailStatus = $this->Listing->User->hasAny(array("onAddedListingApproval"=>1,'User.id'=>$userData['id']));
		if($emailStatus == 1 && $listingData['Listing']['status'] == Listing::PUBLISH)
		{
			App::import('Vendor','EmailOperation');
			EmailOperation::sendMail("mailOnListingPublish",array($this,$listingData,$userData));
		}
	}
	
	function admin_edit($id = null)
	{		
		$this->pageTitle = __('Listings');
		$this->Listing->recursive = -1;
		$listingData = $this->Listing->findById($id);
		if(empty($listingData))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect(array('action'=>'admin_index'));		
		}
		$listCategoryIds = $listingData['Listing']['category_list'];
		if($this->data  && isset($this->data['Listing']['category_list']))
		{
			$listCategoryId = $this->data['Listing']['category_list'];
		}
		$allowMultipleCategories = cr("ListingConfig.allow_multiple_categories");
		$EffectivePlan = null;
		if(AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listingData['Listing']['id']);
			if($EffectivePlan)
			{
				$allowMultipleCategoriesPlanValue = $EffectivePlan->allowMultipleCategories();
				if(!is_null($allowMultipleCategoriesPlanValue))
				{
					$allowMultipleCategories = $allowMultipleCategoriesPlanValue;
				}
			}
		}
		$this->set("allowMultipleCategories",$allowMultipleCategories);
		$categories = cri('ListCategory')->getOptions();
		$this->set('categories',$categories);
		$this->prepareListingForm($listCategoryIds,$listingData,$EffectivePlan);
		if($this->data)
		{
			$this->data['Listing']['additional_categories'] = array();
			foreach((array)$this->data['Listing']['categories'] as $categoryId)
			{
				if($categoryId && array_key_exists($categoryId,$categories))
				{
					$this->data['Listing']['additional_categories'][] = array('list_category_id'=>$categoryId);
				}
			}
			$doSave = true;
			if(!count($this->data['Listing']['additional_categories']))
			{
				$doSave = false;
				$this->Listing->invalidate("categories","Please select categories");
			}
			$dataCategories = $this->data['Listing']['categories'];
			if(!is_array($dataCategories))
			{
				$dataCategories = array($dataCategories);
			}
			$dataCategories = @array_values($dataCategories);
			$this->data['Listing']['list_category_id'] = $dataCategories[0];
			$this->data['Listing']['id'] = $listingData['Listing']['id']; 
			if($doSave && $this->save($this->data,true))
			{
				$msg = __('Listing has been updated.');
				$this->successMsg($msg);
				$this->redirect(array("action"=>"index"));
			}else
			{
				$this->errorMsg(__('Sorry, listing could not be updated.'));
			}
		}else
		{
			$this->data = $listingData;
			$this->data['Listing']['categories'] = $this->data['Listing']['category_list'];
		}
		$listingAssets = $this->Listing->ListingAsset->find('all',array("conditions"=>array('listing_id'=>$listingData['Listing']['id']),'recursive'=>-1));	
		$this->set("listingAssets",$listingAssets);
		$this->set("listingData",$listingData);
		$this->set("showImageTab",true);
		$this->helpers[] = "Assets.Asset";
	}
	
	function edit($slug = null)
	{		
		//scope is necessary,since we don't want unplushied listing to be edited by owner. 
		$this->Listing->setScope('published');
		$editing = true;
		$listingData  = $this->Listing->find("first",array("conditions"=>array("Listing.slug"=>$slug),'recursive'=>-1));			
		//checks Configuration here
		if(!$listingData)
		{
			$this->__invalidUrl(__("Invalid URL."));
		}
		if($this->allowListingEdit($listingData) === false)
		{
			$this->__invalidUrl(__("You don't have permission to edit this listing."));
		}
		$categories = cri('ListCategory')->getOptions();
		$this->set('categories',$categories);
        $isOwnerEdit = (cr("ListingConfig.business_owner") && $listingData['Listing']['owner_id'] &&  $this->Session->read("Auth.User.id") == $listingData['Listing']['owner_id']);
		$this->set("listingData",$listingData);
		$categoryIds = $listingData['Listing']['category_list'];
		$allowMultipleCategories = cr("ListingConfig.allow_multiple_categories");
		$EffectivePlan = null;
		$maxImageCount = false;
		if(AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listingData['Listing']['id']);
			if($EffectivePlan->limitImages() == true)
			{
				$maxImageCount = $EffectivePlan->getAllowedTotalImagesCount();
			}
			if($EffectivePlan)
			{
				$allowMultipleCategoriesPlanValue = $EffectivePlan->allowMultipleCategories();
				if(!is_null($allowMultipleCategoriesPlanValue))
				{
					$allowMultipleCategories = $allowMultipleCategoriesPlanValue;
				}
			}
		}
		$this->set("allowMultipleCategories",$allowMultipleCategories);
		
		$this->prepareListingForm($categoryIds,$listingData,$EffectivePlan);
		if($this->data)
		{
			$this->data['Listing']['status'] = $listingData['Listing']['status'];
			$this->data['Listing']['id'] = $listingData['Listing']['id'];
			$doSave = true;
			if($isOwnerEdit)
			{
				$this->data['Listing']['additional_categories'] = array();
				foreach((array)$this->data['Listing']['categories'] as $categoryId)
				{
					if($categoryId && array_key_exists($categoryId,$categories))
					{
						$this->data['Listing']['additional_categories'][] = array('list_category_id'=>$categoryId);
					}
				}
				
				if(!count($this->data['Listing']['additional_categories']))
				{
					$doSave = false;
					$this->Listing->invalidate("categories","Please select categories");
				}
				$dataCategories = $this->data['Listing']['categories'];
				$dataCategories = @array_values($dataCategories);
				$this->data['Listing']['list_category_id'] = $dataCategories[0];
			}else
			{
				unset($this->data['Listing']['additional_categories']);
				unset($this->data['Listing']['list_category_id']);
				unset($this->data['AdditionalCategory']['additional_categories']);
			}
			if($doSave && $this->save($this->data,true,$isOwnerEdit))
			{
				$msg = __('Listing has been updated.');
				$this->Listing->clearScope('published');	//as if moderation is enabled then listing record will not be fetched with scope applied.
				$listingData  = $this->Listing->find("first",array("conditions"=>array("Listing.id"=>$listingData['Listing']['id']),'recursive'=>-1));
				$this->Listing->setScope('published');		//applied scope again
				$url = $listingData['Listing']['viewUrl'];
				if($listingData['Listing']['status'] == Listing::UNPUBLISH)
				{
					App::import('Vendor','EmailOperation');
					EmailOperation::MailOnEditListing($this, $listingData);
					$msg = __("Listing has been updated and will be published after moderation.");
					$url = array('action'=>"index");
				}
				$this->successMsg($msg);
				$this->redirect($url);
			}
		}else
		{
			$this->data = $listingData;
			$this->data['Listing']['categories'] = $this->data['Listing']['category_list'];
		}
		$listingAssets = array();
		//only owner uploaded assets.
		if($isOwnerEdit)
		{
			$listingAssets = $this->Listing->ListingAsset->find('all',array("conditions"=>array("status"=>ListingAsset::PUBLISHED,'listing_id'=>$listingData['Listing']['id']),'recursive'=>-1));
		}
		$this->set("isOwnerEdit",$isOwnerEdit);
		$this->set("maxImageCount",$maxImageCount);
		$this->set("listingData",$listingData);
		$this->set("listing",$listingData);
		$this->set("listingAssets",$listingAssets);
		$this->set("showImageTab",$isOwnerEdit== true);
		
		$this->helpers[] = "Assets.Asset";
	}
	protected function prepareListingForm($categoryIds,$listing = false,$plan = null)
	{
		if(!is_array($categoryIds))
		{
			$categoryIds = array($categoryIds);
		}
		$this->Listing->setEavStatus(true);
		$this->_appyHtmlEditorConfig();
		$this->_isTagEnabled();
		$listingDefaultFieldProperties = array();
		$listingDefaultFields = $this->Listing->getDefaultFields();
		foreach($listingDefaultFields as $fieldName)
		{
			$listingDefaultFieldProperties[$fieldName] = $this->Listing->getFieldProperties($fieldName);
		}
	    $this->Listing->setCategory($categoryIds,$plan);
		$this->set("listingDefaultFields",$listingDefaultFieldProperties);
		//#5980
		if($categoryIds && $listing===false && cr("ListingConfig.add_review_with_listing"))
	    {
			$categoryId = $categoryIds[0];
	    	$this->Listing->Review->setCategoryId($categoryId);
	    }
	    //#5980
		$this->helpers[] = "Tabs";
	}
	protected function save($data = null,$editing = false,$isOwner = false)
	{
		if(!isset($this->params['admin']) && (($editing == false && cr('ListingConfig.enable_moderation')) || (cr("ListingConfig.moderateOwnnerEdit") && !$isOwner)))
		{
			$data['Listing']['status'] = Listing::UNPUBLISH;
		}
		if(isset($data['Listing']['title']))
		{
			$data['Listing']['title'] = trim($data['Listing']['title']);
		}
		$this->Listing->create();
		$defaultListingAssetId = null;
		if($editing && isset($data['ListingAsset']['is_default']) && ($isOwner || isset($this->params['admin']) ) )
		{
			$defaultListingAssetId = $data['ListingAsset']['is_default'];
			unset($data['ListingAsset']);
		}
		if(!$editing || ($editing && ($isOwner || isset($this->params['admin'])) && !$defaultListingAssetId && !$this->Listing->hasDefaultImage($data['Listing']['id'])))
		{
			if(isset($data['Listing']['asset_inputs']) && !empty($data['Listing']['asset_inputs']))
			{
				foreach($data['Listing']['asset_inputs'] as $key=>$assetInput)
				{
					if(isset($assetInput['name']['name']) && $assetInput['name']['name'] && $assetInput['name']['error'] == 0)
					{
						$assetInput['is_default'] = 1;
						$data['Listing']['asset_inputs'][$key] = $assetInput;
						break;
					}
				}
			}
		}
		if($this->Listing->saveAll($data,array('validate'=>'first')))
		{
			if($defaultListingAssetId)
			{
				$this->Listing->ListingAsset->makeAsDefault($this->Listing->id,$defaultListingAssetId);
			}
			return true;
		}else
		{
			return false;			
		}
	}
	
	function view($slug = null)
	{
		$this->actionId = 'listingpages';
		$listingId = $this->Listing->field('id',array('slug'=>$slug)); 
		
		if($listingId == false)
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect(array('action'=>'index'));		
		}
		$listingDefaultFields = $this->Listing->fieldProperties;
		$listCategoryId = $this->Listing->field('list_category_id',array('id'=>$listingId));
		$this->Listing->setCategory($listCategoryId);
		$this->Listing->unbindModel(array('hasMany'=>array('className'=>'Review')),false);
		$this->Listing->setEavStatus(true);
		$this->Listing->unbindModel(array('belongsTo'=>array('User')),false);
		$listingData = $this->Listing->find('first',array('conditions'=>array('Listing.slug'=>$slug,'Listing.status'=> Listing::PUBLISH),'recursive'=>0));
		$this->Listing->setEavStatus(false);
		if(empty($listingData))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect(array('action'=>'index'));		
		}
		$imageLimit = null;
		if(AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listingId);
			if($EffectivePlan->limitImages() == true)
			{
				$imageLimit = $EffectivePlan->getAllowedTotalImagesCount();
				$imageLimit--;
			}
		}
		$listingAssets = array();
		if(is_null($imageLimit) || $imageLimit > 0)
		{
			$listingAssets = $this->Listing->ListingAsset->find('all',array('conditions'=>array('status'=>ListingAsset::PUBLISHED,'is_default'=>0,'listing_id'=>$listingId),
					'order'=>array('created DESC'),'recursive'=>-1,'limit'=>$imageLimit));	
		}
		
		$this->Listing->id = $listingId;
		$this->Listing->saveField('views_count',$listingData['Listing']['views_count']+1, false, false);
		
		$hasReviewd = $this->Listing->Review->hasReviewed($listingId,$this->Session->read('Auth.User.id'));
		$this->set(compact('listingData','hasReviewd'));
		$this->pageTitle = $listingData['Listing']['title'];
		$editorialReview = $this->Listing->Review->getEditorialReview($listingId);
		
		$this->set('editorialReview',$editorialReview);
		$this->set('ListingModelObj',$this->Listing);
		$this->set("metaInformation",cri("MetaInformation")->getMetaInformation($this->Listing->alias,$listingId));
		$this->set('metaKeywords',$listingData['Listing']['meta_keywords']);
		$this->set('metaDescription',$listingData['Listing']['meta_description']);
		$this->set(compact('listingAssets','listingDefaultFields'));
		//@GEOMAP INTERSECTION.
		$this->helpers[] = "GeoMap";
		//setting bread crumb information
		$categoryPaths = $this->Listing->ListCategory->getPath($listingData['Listing']['list_category_id'],null,-1);
		
		//added for showing/change url of breadcrumbs on basis of category from where it was redirected
		if(cr("ListingConfig.allow_multiple_categories"))
		{
			if(isset($this->params['named']['showAsListingCategory']) && $this->params['named']['showAsListingCategory'])
			{
				$categoryIdForCrumb = $this->Listing->ListCategory->field('id',array('ListCategory.slug'=>$this->params['named']['showAsListingCategory']));
				$categoryPaths = $this->Listing->ListCategory->getPath($categoryIdForCrumb,null,-1);
			}
		}
		//added for showing/change url of breadcrumbs on basis of category from where it was redirected
		
		$showDealAddButton = false;
		if(cr("DealConfig.enable_deals"))
		{
			$deals = cri("Deals.Deal")->getListingDeals($listingId);
			if(count($deals)>0)
			{
				$this->set("deals",$deals);
			}
			$showDealAddButton = true;
		}
		$this->set(compact('showDealAddButton'));
		
		$showCategoryCrumb = true;
		$this->set(compact('categoryPaths','showCategoryCrumb'));
		
		//for canonical URL
		$this->set('metaCanonicalUrl',$listingData['Listing']['viewUrl']);
	}	
	
	function home()
	{
		$this->hideLayoutTitle();	
		$this->pageTitle = __("Home");
		
		$this->actionId = 'home';
	}
	
	function _isTagEnabled()
	{
		$isTagEnabled = cr("GeneralConfig.enable_tags");
		$this->set('isTagEnabled',$isTagEnabled);
	}
	
	function admin_change_feature_status($id)
	{
		if($id)
		{
			$action='remove';
			$featureValue = $this->Listing->field('is_featured',array('id'=>$id));
			if($featureValue !=1)
				$action = 'add';
			if($action == 'add')
			{
				$this->Listing->makeFeatured($id);				
			}
			if($action=='remove')
			{
				$this->Listing->removeFeatured($id);
			}
			$this->successMsg(__('Your action has been performed'));
		}
		$this->redirect($this->referer());	
	}
	
	function admin_index()
	{
		if(isset($this->params['named']['search']))
		{
			//doing this due to samrtl link probelem
			$this->admin_search();	
		}else
		{
			$showCustomFields = false;
			if(isset($this->params['named']['category']))
			{
				$listCategoryId = $this->params['named']['category'];
				
				$this->Listing->setCategory($listCategoryId);
				$this->paginate['conditions'] = array('Listing.list_category_id'=>$listCategoryId);
				$showCustomFields = true;	
			}
			$this->pageTitle = __('Listings');
			$this->paginate['contain'] = array('ListCategory');
			$this->paginate['order'] = array('Listing.status ASC','Listing.created DESC');
			$this->paginate['limit'] = 10;
			$listingData = $this->paginate();
			$this->set('listingData',$listingData);
			$this->set('showCustomFields',$showCustomFields);
			
		}
		
	}
	
	function admin_view($id = null)
	{
		$this->Listing->recursive = 0;

		$listingDefaultFields = $this->Listing->fieldProperties;
		$listCategoryId = $this->Listing->field('list_category_id',array('Listing.id'=>$id));
		$this->Listing->setCategory($listCategoryId);
		
		$listingData = $this->Listing->findById($id);
		if(empty($listingData))
		{
			$this->__invalidUrl(null,array('action'=>'admin_index'));
		}
		$this->pageTitle = sprintf(__('%s Listing'),$listingData['Listing']['title']);
		$this->set('listingData',$listingData);
		$this->set('ListingModelObj',$this->Listing);
		$this->set('listingDefaultFields',$listingDefaultFields);
			
	}
	
	
	function admin_delete($id = null)
	{
		$listingData = $this->Listing->findById($id);
		if(empty($listingData))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect(array('action'=>'admin_index'));		
		}
		$this->Listing->setCategory($listingData['Listing']['list_category_id']);
		if($this->Listing->del($id,true))
		{
			cri('ListCategory')->clearRecordCache($listingData['Listing']['list_category_id']);
			cri('Modules.Module')->clearModuleSpecificCache('CategoryList');
			GigaCache::delete('home_categories');
			$this->successMsg(__('Listing has been deleted.'));
			$this->redirect(array('controller'=>'listings','action'=>'admin_index'));	
		}else
		{
			$this->errorMsg(__('Sorry, listing could not be deleted.'));
		}
	}
	
	function admin_changeStatus($id = null)
	{
		$listingData = $this->Listing->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
		if(empty($listingData))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		$this->Listing->setCategory($listingData['Listing']['list_category_id']);		
		$listingStatus = $listingData['Listing']['status'];
		if($listingStatus == Listing::PUBLISH)
		{
			$statusToSave = Listing::UNPUBLISH;
			$successMessage =  __('Listing has been unpublished.');
			$errorMessage =  __('Listing could not be unpublished.');
		}else
		{
			$statusToSave = Listing::PUBLISH;
			$successMessage =  __('Listing has been published.');
			$errorMessage = __('Listing could not be published.');
		}
		$this->Listing->id = $id;
		if($this->Listing->saveField('status',$statusToSave))
		{
			if($statusToSave == Listing::PUBLISH)
			{
				$this->__sendApprovalEmail($id);
			}else
			{
				
			}
			$this->successMsg($successMessage);
		}else
		{
			$this->errorMsg($errorMessage);
		}	
		
		$this->redirect($this->referer());
	}
	

	function __newListings()
	{
		if($this->RequestHandler->isRss())
		{
			$this->pageTitle = __('Most Recent Listings');
		}		
		$this->paginate['order'] = array('Listing.created DESC');
	}
	
	function __myListings()
	{		
		$userId = $this->Session->read('Auth.User.id');
		if(empty($userId))
		{
			$this->__invalidUrl();
		}
		//$this->set('user',array('User'=>$this->Session->read('Auth.User')));
		if(AppUtility::allowPaidListing())
		{
			$this->paginate['conditions']['OR'][] = array('Listing.user_id' => $userId);
			$this->paginate['conditions']['OR'][] = array('Listing.owner_id' => $userId);
		}else
		{
			$this->paginate['conditions'][] = array('Listing.user_id' => $userId);
		}
	}
	
	function __userListings()
	{
		if(!isset($this->params['named']['user']) && @$this->params['pass']['1'] != 'my')
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		
		$userSlug = $this->params['named']['user'];
		$user = $this->Listing->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		$this->set('user',$user);
		if(empty($user))
		{
			$this->__invalidUrl();
		}					
		$this->paginate['conditions'][] = array('Listing.user_id' => $user['User']['id']);
		$this->pageTitle = sprintf(__('%s \'s Listings'),$user['User']['display_name']);
	}	
	function __ownerListings()
	{
		$this->actionId = "owner_listings";
		if(!$this->Session->read('Auth.User.id') || !cr("ListingConfig.business_owner"))
		{
			$this->__invalidUrl();
		}
		$this->paginate['conditions'][] = array('Listing.owner_id' => $this->Session->read("Auth.User.id"));
		$this->pageTitle = __("My Owned Listings");
	}
	function __userFavoriteListings()
	{
		if(!isset($this->params['named']['user']) && $this->params['pass'][0]!="myfavorite")
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		$myfavorite = false;
		if(@$this->params['pass'][0] == "myfavorite")
		{
			$myfavorite = true;
			$userSlug = $this->Session->read('Auth.User.slug');
		}else
		{
			$userSlug = $this->params['named']['user'];
		}
		$user = $this->Listing->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		
		if(empty($user))
		{
			$this->__invalidUrl();
		}
		$userId = $user['User']['id'];	
		$condition = array('UserFavorite.user_id'=>$userId,'UserFavorite.type'=>'Listing');
		$listingIds = cri('Users.UserFavorite')->find('list',array('fields'=>array('item_id'),'conditions'=>$condition));
		$this->paginate['limit'] = 10;
		$this->paginate['order'] = array('Listing.created DESC');	
		$this->paginate['conditions'] = array('Listing.id'=>$listingIds);
		if($myfavorite == false)
		{
			$this->pageTitle = sprintf(__('%s \'s Favorite Listings'),$user['User']['display_name']);			
		}
		$this->set('user',$user);
	}
	
	function __advancedSearchResuts()
	{	
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = "advancedSearch";
		}
		if($this->referer() != '/'.$this->params['url']['url'])
		{
			$this->Session->write('referer',$this->referer());
		}
		$referer = $this->Session->read('referer');
		App::import('Vendor','ListingSearch');
		$categoryId = $this->params['pass'][1];
		$fields = $this->Listing->getSearchFields($categoryId);
		$customFields = $this->Listing->getAttributes()->getFields();
		//to accomodate all custom fields.
		$fields = am($customFields,$fields);
		$fields = array_unique($fields);
		$GigaSearch = new ListingSearch($this->Listing);
		$query = $GigaSearch->toDataFromUrl($fields,$this->params['named']);
		$this->data['Listing'] = $query;
		//@GEOMAP INTERSECTION.
		if(cr("MapConfig.show_distance") && cr("MapConfig.search_field") && in_array(cr("MapConfig.search_field"),$fields) && isset($this->data['Listing'][cr("MapConfig.search_field")]))
		{
			if(isset($this->params['named']['sort']) && $this->params['named']['sort'] == "Listing.distance")
			{
				$this->paginate['distanceOrder'] = $this->params['named']['direction'];
			}else if(!isset($this->params['named']['sort']))
			{
				$this->paginate['distanceOrder'] = "asc";
			}
			$addressData = $this->data['Listing'][cr("MapConfig.search_field")];
			if(cr('MapConfig.radius_metric') == "km")
			{
				//convert to Miles.
				$addressData['distance'] = Utility::kmToMiles($addressData['distance']);
			}
			$this->paginate['distance'] = $addressData['distance'];
			$this->paginate['location'] = $addressData['address'];
			$addressData['latLng'] = cri("Geo.Geocode")->getCordinates(array("address"=>$addressData['address']));
			$this->set("distanceSearch",$addressData);
			unset($query[cr("MapConfig.search_field")]);
		}
		$condition = array();
		if($query)
		{
			$condition = $GigaSearch->createConditions($fields,$query);
		}
		$categoryIds = $this->Listing->ListCategory->getCategoryTreeList($categoryId);
		$categoryIds  = array_flip($categoryIds);
		array_push($categoryIds, $categoryId);
			
		$condition['Listing.list_category_id'] = $categoryIds;
		$this->paginate['conditions'] = $condition;
		if($referer != '/listings/advancedSearch')
		{
			$this->set('referer',$referer);
		}	
	}
	function __mostViewedListings()
	{
		$this->paginate['order'] = array('Listing.views_count DESC');
	}
	
	function __categoryListings()
	{	
		$categorySlug = $this->params['named']['category'];
		$categoryData = $this->Listing->ListCategory->find('first',array('recursive'=>-1,'conditions'=>array('ListCategory.slug'=>$categorySlug)));
		if(empty($categoryData))
		{
			$this->__invalidUrl();
		}
		$this->actionId = 'categorypages';
		$this->actionParams = array('categorySlug' => $categorySlug);
		$this->pageTitle = __('Categories');
		$viewFile = "category";
		$rssCategoryName = $categoryData['ListCategory']['name'];		
		if(!$this->params['isAjax'] && !$this->RequestHandler->isRss())
		{
			$hideRssFeed = cr('ListingConfig.disable_listing_rss');
			$children = $this->Listing->ListCategory->children($categoryData['ListCategory']['id'],true);
			$categoryPaths = $this->Listing->ListCategory->getPath($categoryData['ListCategory']['id'],null,-1);
			$this->set(compact('categoryPaths','categoryData','children','hideRssFeed'));
			$pageTitle = $categoryData['ListCategory']['name'];
		}else
		{
			$pageTitle = sprintf(__('Listings of category %s'),$rssCategoryName);
		}
        if(!$this->RequestHandler->isRss())
		{
          $this->viewFile = $viewFile;
        }
        $categoryId = $categoryData['ListCategory']['id'];
		$categoryIds = $this->Listing->ListCategory->getCategoryTreeList($categoryId);
		$categoryIds  = array_flip($categoryIds);
		array_push($categoryIds, $categoryId);
		$this->paginate['conditions']['OR']['Listing.list_category_id'] = $categoryIds;
        if(cr('ListingConfig.allow_multiple_categories'))
        {
			$this->paginate['conditions']['OR']['AdditionalCategory.list_category_id'] = $categoryIds;
			$this->paginate['joins'][] = array(
				"alias" => "AdditionalCategory",
				"table" => cri("AdditionalCategory")->table,
				"conditions" => array("AdditionalCategory.listing_id = Listing.id"),
				"type" => "LEFT",
				"foreignKey" => false
			);
			$this->paginate['group'] = "Listing.id";
        }
		$this->pageTitle = $pageTitle;
		//code to set rss info starts here
		$channelData = array('description'=>'Category:'.$rssCategoryName, 'title'=>$rssCategoryName.' Category RSS');
		//code to set rss info ends here			
		$this->set('channel',$channelData);
		//$this->set("category",$categoryData);
		$this->set("metaInformation",cri("MetaInformation")->getMetaInformation($this->Listing->ListCategory->alias,$categoryId));		
	}
	
	function __tagListings()
	{
		if(!isset($this->params['pass']['1']))
		{
			$this->__invalidUrl("Invalid tag!");
		}
		$tagToFind = $this->params['pass']['1'];
		$tagId = cri("Tags.Tag")->field('id',array('Tag.slug'=>$tagToFind));
		$itemIds = cri('Tags.TaggedItem')->find('list',array('fields'=>array('TaggedItem.item_id'),'conditions'=>array('TaggedItem.tag_id'=>$tagId,'type'=>'Listing')));
		
		if(empty($itemIds))
		{
			$this->__invalidUrl();	
		}
		$this->pageTitle = sprintf(__('%s tagged listings'),$tagToFind);
		$this->paginate['conditions'][] = array('Listing.id'=>$itemIds);		
	}
	
	function __invalidUrl($msg = null, $url = null)
	{
		if(empty($msg))
		{
			$msg = __("Invalid URL");
		}
		if(empty($url))
		{
			$url = "/";
		}
		$this->errorMsg($msg);
		$this->redirect($url);
	}
	
	function __featuredListings($limit = null)
	{
		if(is_null($limit))
		{
			$limit = 1;
		}
		$featuredListingIds = $this->Listing->getLastFeatured($limit);
		$order = array();
		if($featuredListingIds)
		{
			$order = array('FIELD(Listing.id,'.implode(',',$featuredListingIds).')');
		}
		$this->paginate['conditions'][] = array('Listing.id'=>$featuredListingIds,'Listing.status'=>Listing::PUBLISH);
		$this->paginate['order'] = $order;				
	}
	
	function advancedSearch($categoryId = null)
	{
		$fields = array();
		$this->pageTitle = __("Advanced search");
		if($categoryId!= null)
		{
			$fields = $this->Listing->getSearchFields($categoryId);	
		}
		if($categoryId && $this->data)
		{
			unset($this->data['__empty']);
			$url  = array();
			if($this->data)
			{
				App::import('Vendor','ListingSearch');
				$GigaSearch = new ListingSearch($this->Listing);
				$url = $GigaSearch->toUrlArray($this->data['Listing']);
			}
			$url = am(array('action'=>"index",'advancedSearch',$categoryId),$url);
			$this->redirect($url);
		}
		$this->set('fields',$fields);
		$this->set('categories',cri('ListCategory')->getOptions());
		$this->set('categoryId',$categoryId);
		$this->helpers[] = 'ListingSearchForm';
	}
	
	function __search()
	{
		$this->actionId = "text_search";
		if(isset($this->data['Listing']['search']))
		{
			$pass = am($this->params['named'],array("?"=>array('search'=>$this->data['Listing']['search'])));
			$pass = am($pass,$this->params['pass']);
			$this->redirect($pass);
		}
		$search = "";
		if(isset($_GET['search']) && strlen($_GET['search']) > 0)
		{
			$search = $_GET['search'];
		}
		$condition = array();
		if(strlen($search) < 1)
		{
			$this->__newListings();
		}else
		{
			
			$condition['OR'] = $this->Listing->getTextSearchCondition($search);
			//Search Categories.
			$listCategoryId = $this->Listing->ListCategory->field('id',array("name"=>$search));
			if($listCategoryId)
			{
				$categoryIds = $this->Listing->ListCategory->getChildrenOptions($listCategoryId);
				$categoryIds = array_keys($categoryIds);
				$categoryIds[] = $listCategoryId;
				$categoryIds = array_unique($categoryIds);
				$condition['OR']['ListCategory.id'] = $categoryIds;
			}
			$condition['OR']['ListCategory.name like'] = "%".$search."%"; 
			$this->pageTitle= sprintf(__("Result for \"%s\""),$search);
		}
		//prd($condition);
		$this->paginate['conditions'] = $condition;
		if($this->RequestHandler->isAjax() == false)
		{
			$this->viewFile = "search_result_combine";
		}
		$this->set("combinedResult",true);
		$this->set('search',$search);
		$this->helpers[] = 'Cms.Tabs';
	}
	
	function __searchLocation()
	{
		$this->actionId = "text_search";
		if($this->data)
		{
            //using named in params give 404 in case back slash (/) in the search term.
            $this->params['named'] = array();
			$this->params['named']['search'] = $this->data['Listing']['search'];
			$this->params['named']['location'] = $this->data['Listing']['location'];
            $this->redirect(am($this->params['pass'],array("?"=>$this->params['named'])));
		}
		$text = $_GET['search'];
		$location = $_GET['location'];
		$conditions = array();
		if($text)
		{
			$conditions['OR'] = $this->Listing->getTextSearchCondition($text);
			$conditions['OR']['ListCategory.name like'] = "%$text%";
			//Search Categories.
			$listCategoryId = $this->Listing->ListCategory->field('id',array("name"=>$text));
			if($listCategoryId)
			{
				$categoryIds = $this->Listing->ListCategory->getChildrenOptions($listCategoryId);
				$categoryIds = array_keys($categoryIds);
				$categoryIds[] = $listCategoryId;
				$categoryIds = array_unique($categoryIds);
				$conditions['OR']['ListCategory.id'] = $categoryIds;
			}
		}
		if($location)
		{
			$locationString = mysql_real_escape_string($location); 
			$conditions[] = "(MATCH(Listing.location_search_cache) AGAINST (\"$locationString\" IN BOOLEAN MODE))";
		}
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
	}
	
	function __searchCategory()
	{
		$this->actionId = "text_search";
		if($this->data)
		{
            //using named in params give 404 in case back slash (/) in the search term.
            $this->params['named'] = array();
			$this->params['named']['search'] = $this->data['Listing']['search'];
			$this->params['named']['category'] = $this->data['Listing']['category'];
                        
            $this->redirect(am($this->params['pass'],array("?"=>$this->params['named'])));
		}
		$text = $_GET['search'];
		$category = $_GET['category'];
		$conditions = array();
		if($text)
		{
			$conditions['OR'] = $this->Listing->getTextSearchCondition($text);
			$conditions['OR']['ListCategory.name like'] = "%$text%";
			//Search Categories.
			$listCategoryId = $this->Listing->ListCategory->field('id',array("name"=>$text));
			if($listCategoryId)
			{
				$categoryIds = $this->Listing->ListCategory->getChildrenOptions($listCategoryId);
				$categoryIds = array_keys($categoryIds);
				$categoryIds[] = $listCategoryId;
				$categoryIds = array_unique($categoryIds);
				$conditions['OR']['ListCategory.id'] = $categoryIds;
			}
		}
		if($category)
		{
			$categoryString = mysql_real_escape_string($category); 
			$conditions[] = "Listing.list_category_id = '$categoryString'";
//			$conditions[] = "(MATCH(Listing.list_category_id) AGAINST (\"$categoryString\" IN BOOLEAN MODE))";
		}
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
	}
	
	//function to show tag index page.
	function tags()
	{
		$this->pageTitle = __("Tags");
		$tagCount = ClassRegistry::init('Tags.Tag')->find('count');
		$this->set(compact('tagCount'));
	}
	
	function admin_search()
	{
		$this->pageTitle = __('Search');
		$default = array(
			'title'=>'',
			'submitter_name'=>'',
			'list_category_id'=>'',
			'status'=>'',
		);
		if($this->data)
		{
			$queryString = '';
			foreach($this->data['Listing'] as $field=>$value)
			{
				$queryString .= $field.':'.$value.'/';
			}		
			//$url = am(array('action'=>'search','prefix'=>'admin'),$this->data['Listing']);
			$this->redirect('/admin/listings/search/'.$queryString);
		}		
			
		$params = am($default,$this->params['named']);
		
		if(!empty($params['title']))
		{
			$this->paginate['conditions']['AND'][] = array('Listing.title LIKE'=>'%'.$params['title'].'%');	
		}
			
		if(!empty($params['submitter_name']))
		{
			$user_ids = $this->Listing->User->find('list',array('fields'=>'User.id','conditions'=>array('username LIKE'=>'%'.$params['submitter_name'].'%')));
			$this->paginate['conditions']['AND'][] = array('Listing.user_id'=>$user_ids);
		}
			
		if(!empty($params['list_category_id']))
		{
            
			$categoryIds = $params['list_category_id'];
            $this->Listing->setCategory($categoryIds);
            $showCustomFields = true;
			$this->paginate['conditions']['AND'][] = array('Listing.list_category_id'=>$categoryIds);
            $this->set("showCustomFields",$showCustomFields);
		}
			
		if($params['status'] !=='')
		{
			if($params['status'] == 'featured')
			{
				$this->paginate['conditions']['AND'][] = array('Listing.is_featured'=>1);		
			}else{
				$this->paginate['conditions']['AND'][] = array('Listing.status'=>$params['status']);
			}	
		}		
		$this->paginate['contain'] = array('ListCategory');
		$this->paginate['order'] = array('Listing.created DESC');
		$this->paginate['limit'] = 10;
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('searchParams',$params);
			$this->Session->write('conditions',$this->paginate['conditions']);
		}	
		$listingData = $this->paginate();	
		$this->set('listingData',$listingData);
		$this->render('admin_index');
	}

	function compare()
	{
		$this->pageTitle = __('Compare Listings');
		$this->layout = 'compare';
		$invalidUrl = false;
		
		if(!isset($this->params['named']['listing_ids']))
		{
			$invalidUrl = true;
		}
		if($invalidUrl)
		{
			$this->__invalidUrl();
		}
		
		$listingIds = $this->params['named']['listing_ids'];
		$explodedListingId = explode(',',$listingIds);
		if($explodedListingId['0'] == '')
		{
			$listingIds = substr($listingIds,1);
			$url = '/listings/compare/listing_ids:'.$listingIds;
			$this->redirect($url);
		}		
		if(isset($this->params['named']['removal_listing']) && !empty($this->params['named']['removal_listing']))
		{
			$explodedListingId = array_diff($explodedListingId,array($this->params['named']['removal_listing']));
			$newListingIds = implode(',',$explodedListingId);
			$redirectUrl = '/listings/compare/listing_ids:'.$newListingIds;
			$this->redirect($redirectUrl);		
		}
		
		
		
		$listingDefaultFields = $this->Listing->fieldProperties;
		//$this->Listing->setEavStatus(true);
		$this->paginate['conditions'] = array('Listing.id'=>array_filter(explode(',',$listingIds)));
		$this->paginate['order'] = array('FIELD(Listing.id,'.$listingIds.')');
		if(isset($this->params['named']['page']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		$listings = $this->paginate();
		$categoryInfo = $this->Listing->ListCategory->find('list',array('fields'=>array('id','name')));
		$this->set('listings',$listings);
		$this->set('categoryInfo',$categoryInfo);
		$this->set('listingDefaultFields',$listingDefaultFields);
		$this->set('ListingModelObj',$this->Listing);
	}
	
	function loadListing()
	{
		Configure::write('debug',0);
		$invalidUrl = false;
		if(!isset($this->params['named']['listing_ids']))
		{
			$invalidUrl = true;
		}
		if($invalidUrl)
		{
			exit;
		}
		
		$listingIds = $this->params['named']['listing_ids'];
		$explodedListingId = explode(',',$listingIds);
		if($explodedListingId['0'] == '')
		{
			$listingIds = substr($listingIds,1);
		}
		$listingDefaultFields = $this->Listing->fieldProperties;
		$this->paginate['conditions'] = array('Listing.id'=>array_filter(explode(',',$listingIds)));
		$this->paginate['order'] = array('FIELD(Listing.id,'.$listingIds.')');
		$listings = $this->paginate();
		$this->set('listings',$listings);
	}

	function admin_editCategory($listingId)
	{
		$this->Listing->recursive = -1;
		$listing = $this->Listing->findById($listingId);
		if(!$listing)
		{
			$this->redirect(array("action"=>"index"));
		}
		if($this->data)
		{
			$this->Listing->id = $listingId;
			if(isset($this->data['Listing']['list_category_id']) && $this->Listing->saveField("list_category_id",$this->data['Listing']['list_category_id']));
			{
				$this->Listing->Review->recursive = -1;
				$this->Listing->Review->updateAll(array('list_category_id'=>$this->data['Listing']['list_category_id']),array("listing_id"=>$listingId));
				GigaCache::delete('home_categories');
				GigaModelCache::delete('ListCategory',$this->data['Listing']['list_category_id'],'listing_count');
				GigaModelCache::delete('ListCategory',$listing['Listing']['list_category_id'],'listing_count');
				$this->successMsg(__("Category has been changed. Please edit the listing information now"));
				$this->redirect(array("action"=>"edit",$listingId));
			}
		}else
		{
			$this->data = $listing;
		}
		$categories = cri('ListCategory')->getOptions();
		$this->set('categories',$categories);
	}

	function suggest()
	{
		$q = null;
		if(isset($_GET['q']))
		{
			$q = $_GET['q'];
		}
		$q = trim($q);
		$suggestions = array();
		$limit = 15;
		if(strlen($q))
		{
			$categories = $this->Listing->ListCategory->find("all",array('conditions'=>array("name like"=>'%'.$q."%"),'recursive'=>-1,'fields'=>array("DISTINCT(name)"),'limit'=>$limit));
			$categories = Set::extract($categories,'{n}.ListCategory.name');
			$suggestions = array_values($categories);
		}
		$limit = $limit - count($suggestions);
		if($limit)
		{
			$condition = $this->Listing->getTextSearchCondition($q,true);
			$condition['AND']['Listing.status'] = Listing::PUBLISH;
			$this->Listing->Behaviors->detach("Eav");
			$listings = $this->Listing->find('all',array('conditions'=>$condition,'fields'=>array("DISTINCT(title)"),'limit'=>$limit,'recursive'=>-1));
			$list = Set::extract($listings,'{n}.Listing.title');
			$suggestions = am($suggestions,$list);
		}
		Configure::write("debug",0);
		if(count($suggestions))
		{
			foreach($suggestions as $suggest)
			{
				echo $suggest.'|'.$suggest."\n";
			}
		}else
			{
				echo __("No result");
			}
		exit;
	}

	function admin_reloadForm($listingId)
	{
		$this->Listing->recursive = -1;
		$this->data = $this->Listing->findById($listingId);
		$this->prepareListingForm($_POST['categoryId'],$this->data);
	}
	function admin_deleteVideo($listingId,$field)
    {
        $this->Listing->deleteVideo($listingId,$field);
        $this->_stop();
    }
    
    function deleteVideo($listingId,$field)
    {
      $this->recursive  = -1;
      $listing = $this->Listing->findById($listingId);
      if($this->allowListingEdit($listing) == false)
      {
        echo "NO ACCESS";
        $this->_stop();
      }
      $this->Listing->deleteVideo($listingId,$field);
      $this->_stop();
    }
    //Check to allow Listing Edit by user or not.
    private function allowListingEdit($listingData)
    {
      	$allowEdit = ($listingData['Listing']['user_id'] != $this->Session->read("Auth.User.id") || !cr("ListingConfig.allowOwnerEdit")) == false;
		//owner is editing the listing.
		$isOwnerEdit = (cr("ListingConfig.business_owner") && $listingData['Listing']['owner_id'] &&  $this->Session->read("Auth.User.id") == $listingData['Listing']['owner_id']);
		$allowEdit = $allowEdit || $isOwnerEdit;
        return $allowEdit;
    }
    function delete($id)
    {
    	$id = $this->Listing->field("id",array("Listing.id"=>$id,'user_id'=>$this->Session->read("Auth.User.id")));
    	if($id && $this->Session->read("Auth.User.id"))
    	{
    		$this->Listing->delete($id);
    		$this->successMsg(__("Your listing has been deleted"));
    		$this->redirect('/listings/index/my');
    	}
    	$this->errorMsg(__("Invalid url"));
    	$this->redirect($this->referer());
    }
    
    function getDirections($listingSlug)
    {
    	$listing = $this->Listing->find("first",array("conditions"=>array("Listing.slug"=>$listingSlug),"recursive"=>0));
    	if(!$listingSlug || empty($listing))
    	{
    		$this->errorMsg(__("Invalid URL"));
    		$this->redirect("/");
    		return;
    	}
    	if (!isset($listing['Listing']['lat']) || !isset($listing['Listing']['lng']) || !$listing['Listing']['lat'] || !$listing['Listing']['lng']) {
    		$this->errorMsg(__("Listing latitude/longitude position not available"));
    		$this->redirect("/");
    		return;
    	}
    	$this->set('listing',$listing);
    }
}
?>